<template>
  <el-upload
    class="avatar-uploader"
    :headers="headers"
    :limit="limit"
    accept=".jpg, .jpeg, .png, .gif"
    :file-list="computedImageUrl"
    list-type="picture-card"
    :action="$uploadPath"
    :on-success="handleImageSuccess"
    :on-remove="handleRemove"
    :on-exceed="uploadOverrun"
  >
    <i class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>
<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'UploadImage',
  props: {
    value: {
      type: Array,
      default: undefined
    },
    limit: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      imageUrlList: []
    }
  },
  computed: {
    computedImageUrl() {
      var obj = []
      if (this.imageUrlList !== undefined && this.imageUrlList.length > 0) {
        for (var i = 0; i < this.imageUrlList.length; i++) {
          obj.push({
            url: this.$downPath + this.imageUrlList[i]
          })
        }
      }
      return obj
    },
    headers() {
      return {
        'Authorization': 'Bearer ' + getToken()
      }
    }
  },
  watch: {
    value() {
      this.imageUrlList = this.value
    }
  },
  created() {
    this.imageUrlList = this.value
  },
  mounted() {
    this.imageUrlList = this.value
  },
  methods: {
    rmImage() {
      this.emitInput('')
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    uploadOverrun() {
      this.error('上传文件个数超出限制!最多上传5张图片!')
    },
    handleRemove(file, fileList) {
      for (var i = 0; i < this.imageUrlList.length; i++) {
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.$downPath + this.imageUrlList[i] === url) {
          this.imageUrlList.splice(i, 1)
        }
      }
    },
    handleImageSuccess(res, file, fileList) {
      if (res.code === '0') {
        if (this.imageUrlList === undefined) {
          this.imageUrlList = []
        }
        this.imageUrlList.push(res.data.url)
        this.emitInput(this.imageUrlList)
      }
    }
  }
}
</script>
